package com.ror.util;

import com.ror.event.GameEvent;
import com.ror.event.GameEventArgs;
import com.ror.event.GameEventType;
import com.ror.event.GameObserver;
import com.ror.game.PokerLabel;

import java.awt.*;
import java.util.ArrayList;

public class AnimationUtil {
    private static final ArrayList<GameObserver> observers = new ArrayList<>();

    public static void addObserver(GameObserver observer) {
        observers.add(observer);
    }

    public static void removeObserver(GameObserver observer) {
        observers.remove(observer);
    }

    public static void notifyObservers(GameEventType eventType, GameEventArgs eventArgs) {
        GameEvent e = new GameEvent(eventType, eventArgs);
        for (GameObserver observer : observers) {
            observer.onGameUpdated(e);
        }
    }

    public static void move(PokerLabel label, Point from, Point to) {
        move(label, from, to, 20);
    }

    //基于y=kx+b的平移动画，不能竖直移动
    public static void move(PokerLabel label, Point from, Point to, int step) {
        //注册为观察者
        addObserver(label);
        if (to.x == from.x) {
            //fallback：无动画，瞬间移动
            label.setLocation(to);
            return;
        }
        double k = (1.0) * (to.y - from.y) / (to.x - from.x);
        double b = to.y - to.x * k;
        step = from.x < to.x ? step : -step;
        for (int xi = from.x; Math.abs(xi - to.x) > Math.abs(step); xi += step) {
            double y = k * xi + b;
            label.setLocation(xi, (int) y);
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        label.setLocation(to);
        notifyObservers(GameEventType.MOVE_ANIMATION_DONE, null);
        //注销观察者，否则它将响应其他动画结束事件
        removeObserver(label);
    }
}
